package br.ufmg.vod.collections;


public class IntQueueStack implements IntQueue, IntStack {
	
	int[] array;
	int first;
	int last;
	public int length;
	final int capacity;

	public IntQueueStack(int capacity){
		this.array = new int[capacity];
		this.capacity = capacity;
		clear();
	}

	/* (non-Javadoc)
	 * @see br.ufmg.vod.jung.collections.IntQueue#clear()
	 */
	public void clear() {
		this.first=0;
		this.last=0;
		this.length=0;
	}
	
	/* (non-Javadoc)
	 * @see br.ufmg.vod.jung.collections.IntQueue#enqueue(int)
	 */
	public void enqueue(int v){
//		System.out.println(v);
		this.array[this.last++%this.capacity] = v;
		this.length++;
	}
	
	/* (non-Javadoc)
	 * @see br.ufmg.vod.jung.collections.IntQueue#dequeue()
	 */
	public int dequeue(){
		this.length--;
		return this.array[this.first++%this.capacity];
	}
	
	/* (non-Javadoc)
	 * @see br.ufmg.vod.jung.collections.IntStack#push(int)
	 */
	public void push(int v){
		this.array[this.last++%this.capacity] = v;
		this.length++;
	}
	
	/* (non-Javadoc)
	 * @see br.ufmg.vod.jung.collections.IntStack#pop()
	 */
	public int pop(){
		this.length--;
		return this.array[--this.last%this.capacity];
	}
	
	/* (non-Javadoc)
	 * @see br.ufmg.vod.jung.collections.IntQueue#isEmpty()
	 */
	/* (non-Javadoc)
	 * @see br.ufmg.vod.jung.collections.IntStack#isEmpty()
	 */
	public boolean isEmpty(){
		return this.length == 0;
	}
	
	public int size(){
		return this.length;
	}
	
	public int peek(int i){
		return this.array[first+i];
	}
	
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder(length*4);
		sb.append(first+":"+last+" ");
		sb.append("[");
		for (int i = first; i < last; i++) {
			sb.append(array[i]);
			sb.append(", ");
		}
		sb.append("]");
		return sb.toString();
	}

	@Override
	public int[] toArray(int[] copy) {
		System.arraycopy(array, first, copy, 0, last-first);
		return copy;
	}

}
